const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs').promises;
const Vehicle = require('../models/Vehicle');
const User = require('../models/User');
const router = express.Router();

// 配置文件上传
const storage = multer.diskStorage({
  destination: async (req, file, cb) => {
    const uploadPath = path.join(__dirname, '../../storage/vehicles');
    try {
      await fs.mkdir(uploadPath, { recursive: true });
      cb(null, uploadPath);
    } catch (error) {
      cb(error);
    }
  },
  filename: (req, file, cb) => {
    const uniqueName = `vehicle_${Date.now()}_${Math.random().toString(36).slice(2)}${path.extname(file.originalname)}`;
    cb(null, uniqueName);
  }
});

const upload = multer({
  storage,
  limits: { fileSize: 10 * 1024 * 1024 }, // 10MB
  fileFilter: (req, file, cb) => {
    const allowedTypes = /jpeg|jpg|png|gif|webp/;
    const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
    const mimetype = allowedTypes.test(file.mimetype);
    
    if (mimetype && extname) {
      return cb(null, true);
    } else {
      cb(new Error('只允许上传图片文件'));
    }
  }
});

/**
 * 获取车辆信息
 */
router.get('/:vehicleId', async (req, res) => {
  try {
    const { vehicleId } = req.params;
    const vehicle = await Vehicle.findByVehicleId(vehicleId);
    
    if (!vehicle) {
      return res.status(404).json({
        code: '40400',
        message: '车辆不存在',
        data: null
      });
    }
    
    res.json({
      code: '20000',
      message: '获取车辆信息成功',
      data: vehicle
    });
    
  } catch (error) {
    console.error('获取车辆信息失败:', error);
    res.status(500).json({
      code: '50000',
      message: '获取车辆信息失败',
      data: null
    });
  }
});

/**
 * 获取用户车辆列表
 */
router.get('/user/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const vehicles = await Vehicle.findByUserId(parseInt(userId));
    
    res.json({
      code: '20000',
      message: '获取车辆列表成功',
      data: vehicles
    });
    
  } catch (error) {
    console.error('获取车辆列表失败:', error);
    res.status(500).json({
      code: '50000',
      message: '获取车辆列表失败',
      data: null
    });
  }
});

/**
 * 上传车辆图片
 */
// 同时兼容字段名 'image' 和 'file'
router.post('/:vehicleId/image', upload.fields([{ name: 'image', maxCount: 1 }, { name: 'file', maxCount: 1 }]), async (req, res) => {
  try {
    const { vehicleId } = req.params;
    // 兼容取文件
    const file = (req.files && (req.files.image?.[0] || req.files.file?.[0])) || null;

    if (!file) {
      return res.status(400).json({
        code: '40000',
        message: '请选择要上传的图片文件',
        data: null
      });
    }
    
    // 解析当前登录用户（从 Authorization: Bearer <token>）
    let currentUserId = null;
    const authHeader = req.headers['authorization'] || req.headers['Authorization'];
    if (authHeader && /^bearer\s/i.test(authHeader)) {
      const token = authHeader.replace(/^bearer\s+/i, '').trim();
      try {
        const user = await User.verifyToken(token);
        currentUserId = user?.id || null;
      } catch (_) {
        currentUserId = null;
      }
    }

    let vehicle = await Vehicle.findByVehicleId(vehicleId);
    if (!vehicle) {
      // 若库结构不允许 user_id 为 NULL，则在未登录情况下不允许自动创建
      if (!currentUserId) {
        return res.status(401).json({
          code: '40100',
          message: '请先登录后再上传车辆图片（无法识别用户，禁止自动创建车辆）',
          data: null,
        });
      }
      // 若车辆不存在，则以最小字段集自动创建一条记录，避免阻塞上传流程
      try {
        await Vehicle.upsert({
          vehicle_id: vehicleId,
          user_id: currentUserId,
          vin: null,
          model: null,
          brand: 'CFMOTO',
          series: null,
          color: null,
          year: null,
          mileage: 0,
          battery_level: null,
          charging_status: null,
          location_lat: null,
          location_lng: null,
        });
        vehicle = await Vehicle.findByVehicleId(vehicleId);
        console.log(`🆕 已为上传自动创建车辆记录: ${vehicleId}`);
      } catch (createErr) {
        console.error('自动创建车辆失败:', createErr?.message);
        return res.status(404).json({
          code: '40400',
          message: `车辆不存在，且自动创建失败: ${createErr?.message || ''}`.trim(),
          data: null
        });
      }
    }
    
    const imagePath = `/storage/vehicles/${file.filename}`;
    const success = await Vehicle.updateCustomImage(vehicleId, imagePath);
    
    if (!success) {
      return res.status(500).json({
        code: '50000',
        message: '图片上传失败',
        data: null
      });
    }
    
    // 计算绝对URL
    // 优先使用公开对外的固定地址，避免经过前端代理时 host 被替换为 FE 域名导致 404
    const publicBase = process.env.PUBLIC_BASE_URL || process.env.SERVER_PUBLIC_ORIGIN || '';
    let absoluteUrl;
    if (publicBase) {
      absoluteUrl = `${publicBase.replace(/\/$/, '')}${imagePath}`;
    } else {
      const host = req.get('host');
      const protocol = (req.protocol || 'http').split(',')[0].trim();
      absoluteUrl = host ? `${protocol}://${host}${imagePath}` : imagePath;
    }

    res.json({
      code: '20000',
      message: '图片上传成功',
      data: {
        // 兼容字段：原有相对路径
        image_path: imagePath,
        // 新增字段：绝对地址，前端可直接展示
        url: absoluteUrl,
        image_url: absoluteUrl,
        file_size: file.size,
        original_name: file.originalname
      }
    });
    
  } catch (error) {
    console.error('图片上传失败:', error);
    res.status(500).json({
      code: '50000',
      message: '图片上传失败',
      data: null
    });
  }
});

/**
 * 同步车辆数据
 */
router.post('/sync', async (req, res) => {
  try {
    const { vehicles } = req.body;
    
    if (!Array.isArray(vehicles)) {
      return res.status(400).json({
        code: '40000',
        message: '车辆数据格式错误',
        data: null
      });
    }
    
    const result = await Vehicle.batchSync(vehicles);
    
    res.json({
      code: '20000',
      message: '车辆数据同步完成',
      data: result
    });
    
  } catch (error) {
    console.error('车辆数据同步失败:', error);
    res.status(500).json({
      code: '50000',
      message: '车辆数据同步失败',
      data: null
    });
  }
});

/**
 * 更新车辆信息
 */
router.put('/:vehicleId', async (req, res) => {
  try {
    const { vehicleId } = req.params;
    // 解析当前登录用户（从 Authorization: Bearer <token>）
    let currentUserId = null;
    const authHeader = req.headers['authorization'] || req.headers['Authorization'];
    if (authHeader && /^bearer\s/i.test(authHeader)) {
      const token = authHeader.replace(/^bearer\s+/i, '').trim();
      try {
        const user = await User.verifyToken(token);
        currentUserId = user?.id || null;
      } catch (_) {
        currentUserId = null;
      }
    }

    const vehicleData = { ...req.body, vehicle_id: vehicleId };
    // 若请求体未显式传 user_id，但识别到了登录用户，则绑定 user_id
    if ((vehicleData.user_id === undefined || vehicleData.user_id === null) && currentUserId) {
      vehicleData.user_id = currentUserId;
    }
    
    const result = await Vehicle.upsert(vehicleData);
    
    res.json({
      code: '20000',
      message: '车辆信息更新成功',
      data: {
        vehicleId: result.vehicleId,
        action: result.action
      }
    });
    
  } catch (error) {
    console.error('更新车辆信息失败:', error);
    res.status(500).json({
      code: '50000',
      message: '更新车辆信息失败',
      data: null
    });
  }
});

/**
 * 删除车辆
 */
router.delete('/:vehicleId', async (req, res) => {
  try {
    const { vehicleId } = req.params;
    const success = await Vehicle.softDelete(vehicleId);
    
    if (!success) {
      return res.status(404).json({
        code: '40400',
        message: '车辆不存在',
        data: null
      });
    }
    
    res.json({
      code: '20000',
      message: '车辆删除成功',
      data: null
    });
    
  } catch (error) {
    console.error('删除车辆失败:', error);
    res.status(500).json({
      code: '50000',
      message: '删除车辆失败',
      data: null
    });
  }
});

module.exports = router;
